// src/message/MessageList.tsx
import React from 'react';
import { Avatar, Button, Empty, Tag, Card, message } from 'antd';
import { 
  MessageOutlined, 
  HeartOutlined, 
  UserAddOutlined, 
  EyeOutlined,
  UserOutlined,
  StarOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

interface UserMessage {
  id: number;
  userId: number;
  fromUserId: number;
  type: 'favorite' | 'recipe_comment' | 'comment_like' | 'follow';
  referenceId: number;
  content: string;
  readFlag: boolean;
  createdAt: string;
}

interface UserInfo {
  id: number;
  uid: string;
  username: string;
  avatar: string;
  followCount: number;
  fanCount: number;
  likeCount: number;
  email?: string;
  createdAt: string;
}

interface MessageListProps {
  messages: UserMessage[];
  activeTab: string;
  onMarkMessageAsRead: (messageId: number) => Promise<void>;
  colorConfig: {
    primary: string;
    primaryDark: string;
    border: string;
    background: string;
    badge: string;
    tabActive: string;
  };
}

// 消息类型配置 - 统一使用棕色系
const getMessageTypeConfig = (colorConfig: any) => ({
  favorite: {
    icon: <StarOutlined />,
    color: colorConfig.primary,
    label: '收藏',
    action: '收藏了你的食谱',
    target: 'recipe' as const
  },
  recipe_comment: {
    icon: <MessageOutlined />,
    color: colorConfig.primary,
    label: '评论',
    action: '评论了你的食谱',
    target: 'recipe' as const
  },
  comment_like: {
    icon: <HeartOutlined />,
    color: colorConfig.primary,
    label: '点赞',
    action: '点赞了你的评论',
    target: 'recipe' as const
  },
  follow: {
    icon: <UserAddOutlined />,
    color: colorConfig.primary,
    label: '关注',
    action: '关注了你',
    target: 'user' as const
  }
});

const MessageList: React.FC<MessageListProps> = ({ 
  messages, 
  activeTab, 
  onMarkMessageAsRead,
  colorConfig 
}) => {
  const navigate = useNavigate();
  const [userInfoMap, setUserInfoMap] = React.useState<{ [key: number]: UserInfo }>({});
  const [loadingUsers, setLoadingUsers] = React.useState<{ [key: number]: boolean }>({});
  const [displayCount, setDisplayCount] = React.useState(4); // 初始显示4条消息

  // 获取消息类型配置
  const MESSAGE_TYPE_CONFIG = getMessageTypeConfig(colorConfig);

  // 构建 API 基础 URL
  const getApiBaseUrl = (): string => {
    if (import.meta.env.DEV) {
      return '/api';
    } else {
      return 'http://218.244.141.86:8080/api';
    }
  };

  // 获取用户详情
  const fetchUserDetails = async (userId: number): Promise<UserInfo | null> => {
    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      if (!token) return null;

      const baseUrl = getApiBaseUrl();
      const apiUrl = `${baseUrl}/users/${userId}`;

      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        credentials: 'include'
      });

      if (response.ok) {
        const userData = await response.json();
        return userData;
      }
      return null;
    } catch (error) {
      console.error('获取用户详情失败:', error);
      return null;
    }
  };

  // 加载用户信息
  const loadUserInfo = async (userId: number) => {
    if (userInfoMap[userId] || loadingUsers[userId]) return;

    try {
      setLoadingUsers(prev => ({ ...prev, [userId]: true }));
      const userInfo = await fetchUserDetails(userId);
      if (userInfo) {
        setUserInfoMap(prev => ({
          ...prev,
          [userId]: userInfo
        }));
      }
    } catch (error) {
      console.error(`加载用户 ${userId} 信息失败:`, error);
    } finally {
      setLoadingUsers(prev => ({ ...prev, [userId]: false }));
    }
  };

  // 处理头像URL
  const processAvatarUrl = (avatar: string): string => {
    let url = avatar || '';
    if (url && !url.startsWith('http') && !url.startsWith('https')) {
      if (url.startsWith('/')) {
        url = `http://218.244.141.86:8080${url}`;
      } else {
        url = `http://218.244.141.86:8080/${url}`;
      }
    }
    return url || 'https://picsum.photos/50/50?random=1';
  };

  // 获取消息类型信息
  const getMessageTypeInfo = (msg: UserMessage) => {
    return MESSAGE_TYPE_CONFIG[msg.type] || {
      icon: <MessageOutlined />,
      color: colorConfig.primary,
      label: '消息',
      action: '发送了消息',
      target: 'recipe' as const
    };
  };

  // 菜谱详情获取函数
  const fetchRecipeDetail = async (recipeId: number) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        return null;
      }

      const baseUrl = getApiBaseUrl();
      const apiUrl = `${baseUrl}/recipe/single?id=${recipeId}`;

      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const data = await response.json();
        if (data && data.value) {
          return data.value;
        }
        return data;
      }
      return null;
    } catch (error) {
      console.error('获取菜谱详情失败:', error);
      return null;
    }
  };

  // 处理消息点击
  const handleMessageClick = async (msg: UserMessage) => {
    if (!msg.readFlag) {
      await onMarkMessageAsRead(msg.id);
    }
    
    const typeInfo = getMessageTypeInfo(msg);
    
    if (typeInfo.target === 'user') {
      navigate(`/user/${msg.fromUserId}`);
    } else {
      try {
        const recipeId = msg.referenceId;

        if (recipeId && !isNaN(recipeId)) {
          const recipeData = await fetchRecipeDetail(recipeId);

          let formattedRecipe;

          if (recipeData) {
            formattedRecipe = {
              id: recipeData.id || recipeId,
              title: recipeData.title || '未知菜谱',
              coverImage: recipeData.coverImage || '',
              description: recipeData.description || '这是一道经典的家常菜，色香味俱全。',
              duration: recipeData.duration || 0,
              difficulty: recipeData.difficulty || 3,
              servings: recipeData.servings || 0,
              likesCount: recipeData.likesCount || 0,
              favoriteCount: recipeData.favoriteCount || 0,
              userId: recipeData.userId || 1,
              createdAt: recipeData.createdAt || new Date().toISOString(),
              updatedAt: recipeData.updatedAt || new Date().toISOString(),
            };
          } else {
            formattedRecipe = {
              id: recipeId,
              title: '加载中的菜谱',
              coverImage: '',
              description: '正在加载菜谱信息...',
              duration: 30,
              difficulty: 3,
              servings: 2,
              likesCount: 0,
              favoriteCount: 0,
              userId: 1,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            };
          }

          navigate(`/recipe/${recipeId}`, { 
            state: { 
              recipe: formattedRecipe,
              fromMessage: true
            } 
          });
        } else {
          message.error('无法找到对应的食谱');
        }
      } catch (error) {
        message.error('跳转失败，请稍后重试');
      }
    }
  };

  // 处理查看按钮点击
  const handleViewClick = async (msg: UserMessage, e: React.MouseEvent) => {
    e.stopPropagation();
    await handleMessageClick(msg);
  };

  // 处理用户头像点击
  const handleAvatarClick = (userId: number, e?: React.MouseEvent<HTMLElement>) => {
    if (e) e.stopPropagation();
    navigate(`/user/${userId}`);
  };

  // 组件挂载时加载所有用户信息
  React.useEffect(() => {
    const uniqueUserIds = Array.from(new Set(messages.map(msg => msg.fromUserId)));
    uniqueUserIds.forEach(userId => {
      if (userId && !userInfoMap[userId]) {
        loadUserInfo(userId);
      }
    });
  }, [messages]);

  if (messages.length === 0) {
    const tabLabels: { [key: string]: string } = {
      'all': '',
      'like': '点赞',
      'reply': '评论', 
      'follow': '关注'
    };
    
    return (
      <Empty
        description={`暂无${tabLabels[activeTab] || ''}消息`}
        style={{ margin: '40px 0', padding: '40px', color: colorConfig.primaryDark }}
      />
    );
  }

  // 加载更多消息
  const handleLoadMore = () => {
    setDisplayCount(prev => prev + 4); // 每次加载4条更多消息
  };

  // 显示的消息列表
  const displayedMessages = messages.slice(0, displayCount);

  return (
    <div>
      <div style={{ 
        maxHeight: '600px',
        overflowY: 'auto',
        paddingRight: '8px',
        scrollbarWidth: 'thin',
        scrollbarColor: `${colorConfig.primary} transparent`
      }}>
        {displayedMessages.map((message) => {
          const typeInfo = getMessageTypeInfo(message);
          const userInfo = userInfoMap[message.fromUserId];
          const username = userInfo?.username || `用户${message.fromUserId}`;
          const avatarUrl = userInfo?.avatar ? processAvatarUrl(userInfo.avatar) : undefined;

          return (
            <Card 
              key={`message-${message.id}`}
              style={{ 
                marginBottom: '16px', 
                border: 'none', 
                boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
                borderRadius: '12px',
                background: message.readFlag 
                  ? 'rgba(255, 253, 248, 0.9)' 
                  : 'rgba(232, 217, 199, 0.3)',
                borderLeft: message.readFlag ? 'none' : `4px solid ${typeInfo.color}`,
                cursor: 'pointer',
                transition: 'all 0.3s ease'
              }}
              onClick={() => handleMessageClick(message)}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-2px)';
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)';
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.05)';
              }}
            >
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: '16px' }}>
                {/* 用户头像 */}
                <Avatar 
                  size={48}
                  src={avatarUrl || 'https://picsum.photos/50/50?random=avatar'}
                  icon={<UserOutlined />}
                  style={{ 
                    backgroundColor: typeInfo.color,
                    flexShrink: 0,
                    cursor: 'pointer'
                  }}
                  onClick={(e) => handleAvatarClick(message.fromUserId, e)}
                />
                
                {/* 消息内容 */}
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                    <span style={{ fontWeight: 'bold', color: colorConfig.primaryDark, fontSize: '14px' }}>
                      {username}
                    </span>
                    <Tag 
                      color={typeInfo.color}
                      style={{ 
                        border: 'none', 
                        borderRadius: '12px',
                        color: colorConfig.primaryDark
                      }}
                      icon={typeInfo.icon}
                    >
                      {typeInfo.label}
                    </Tag>
                    {!message.readFlag && (
                      <Tag 
                        color={colorConfig.badge} 
                        style={{ 
                          border: 'none', 
                          borderRadius: '12px', 
                          fontSize: '10px',
                          color: 'white'
                        }}
                      >
                        新
                      </Tag>
                    )}
                  </div>
                  
                  <div style={{ marginBottom: '8px', color: colorConfig.primaryDark, fontSize: '14px' }}>
                    {typeInfo.action}
                    {message.content && `：${message.content}`}
                  </div>
                  
                  <div style={{ fontSize: '12px', color: colorConfig.primaryDark, opacity: 0.7 }}>
                    {new Date(message.createdAt).toLocaleString()}
                  </div>
                </div>
                
                {/* 操作按钮 */}
                <Button 
                  size="small" 
                  icon={<EyeOutlined />}
                  onClick={(e: React.MouseEvent) => handleViewClick(message, e)}
                  style={{
                    borderRadius: '16px',
                    backgroundColor: typeInfo.color,
                    borderColor: typeInfo.color,
                    color: colorConfig.primaryDark,
                    fontWeight: 'bold'
                  }}
                >
                  查看详情
                </Button>
              </div>
            </Card>
          );
        })}
      </div>
      
      {/* 加载更多按钮 */}
      {displayCount < messages.length && (
        <div style={{ textAlign: 'center', marginTop: '16px' }}>
          <Button 
            type="default"
            onClick={handleLoadMore}
            style={{
              borderRadius: '20px',
              fontWeight: 'bold',
              borderColor: colorConfig.border,
              color: colorConfig.primaryDark
            }}
          >
            加载更多
          </Button>
        </div>
      )}
    </div>
  );
};

export default MessageList;